const Koa = require('koa');

const app = new Koa();

const path = require('path');

const router = require('koa-router')();

const query = require('./db/index');

// const bodyparser = require('koa-bodyparser');
const bodyparser = require('./middleware/bodyparser');

let getTime = require('./middleware/getTime');

//获取每次请求消耗的时间
app.use(getTime());

//静态资源
const static = require('koa-static');
//挂在静态资源的中间件
app.use(static(path.join(__dirname,'./public')));

//处理前端传递的参数，放到ctx.request.body上
app.use(bodyparser());

//挂在路由的中间件
app.use(router.routes());

app.use(router.allowedMethods());

//查询

router.get('/api/list',async (ctx) => {
    let {pagenum=1,limit=2} = ctx.query;
    //pagenum 第几页的数据  limit:每页的条数
    let startIndex = (pagenum-1)*limit; //起始的下标
    let list = await query(`select * from userlist limit ${startIndex},${limit}`);
    let total = await query('select count(*) from userlist');

    console.log("total",total)
    ctx.body = {
        code:1,
        data:list,
        total:total[0]['count(*)']
    }
})

//插入
router.post('/api/add',async (ctx) => {
    console.log("====",ctx.request.body)
    let {username,ticket} = ctx.request.body;
    console.log(username,ticket)
    //容错处理
    if(username && ticket){

        //1.排重
        let target = await query('select * from userlist where username=?',[username]);
        console.log(target);
        if(target.length){
            //如果存在，不添加
            ctx.body = {
                code:3,
                msg:'此用户名已存在'
            }
        }else{
            //如果不存在，我们添加
            //try {} catch(e){}  错误处理机制
            try{
                //尝试执行 ....
                await query('insert into userlist (username,ticket) values (?,?)',[username,ticket]);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){ //e:错误对象
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数不全'
        }
    }
})

//删除
router.delete('/api/del',async (ctx) => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from userlist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数不全'
        }
    }
})

//修改
router.put('/api/update',async ctx => {
    console.log(ctx.request.body)
    let {username,ticket,id} = ctx.request.body; //id：要修改数据的id
    //容错处理
    if(username && ticket && id){
        //try {} catch(e){}  错误处理机制
        try{
            //尝试执行 ....
            await query('update userlist set username=?,ticket=? where id=?',[username,ticket,id]);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){ //e:错误对象
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数不全'
        }
    }
})

//登录

//注册
router.post('/api/registry',async ctx => {
    let {username,password}  = ctx.request.body;
    //1.容错处理
    if(username && password){
        // 2.排重
        let target = await query('select * from list where username=?',[username]);
        console.log(target);
        if(target.length){
            //已经注册，用户名已经使用
            ctx.body = {
                code:3,
                msg:'此用户名已经被使用'
            }
        }else{
            // 3.注册
            try{
                await query('insert into list (username,password) values (?,?)',[username,password]);
                ctx.body = {
                    code:1,
                    msg:'注册成功'
                }
            }catch(e){  //e：错误对象
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数不全'
        }
    }
})

//登录
router.post('/api/login',async ctx => {
    let {username,password} = ctx.request.body;
    if(username && password){
        let target = await query('select * from list where username=? and password=?',[username,password]);
        if(target.length){
            ctx.body = {
                code:1,
                msg:'登录成功'
            }
        }else{
            ctx.body = {
                code:0,
                msg:'登录失败'
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数不全'
        }
    }
})

app.listen(3000,() => {
    console.log("服务启动成功")
})

/**
 * 增：insert into  表名 (字段1,字段2,...) values (?,?,...)   字段的数量和values里问号的数量是一致的
 * 
 * 删：delete from 表名 where 条件1=?
 * 
 * 改：update 表名  set 字段1=?,字段2=? where 条件1=?
 * 
 * 查：select * from 表名   *：所有的字段
 * 
 * 
 * 需求：1.获取每次的消耗的时间
 * 
 *      2.封装bodyparser
 * 
*/